#include "common.c"

void loop(int sock) {
    static char buf[1024];
    
    while (1) {
        struct sockaddr_in addr;
        socklen_t addr_len = sizeof(struct sockaddr_in);
        ssize_t r = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addr_len);
        if (r <= 0 || !send_all(sock, buf, r, &addr, addr_len)) {
            break;
        }
    }
}

int main() {
    struct sockaddr_in addr;
    
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket");
        return 1;
    }
    
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    
    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind");
        return 1;
    }
    
    while (1) loop(sock);
}
